package cn.seaboot.word;

import cn.seaboot.html.HtmlReader;
import cn.seaboot.word.html.BodyReader;
import cn.seaboot.word.html.ParagraphReader;
import cn.seaboot.word.html.RunReader;
import cn.seaboot.word.html.TableCodeReader;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Iterator;

/**
 * 将 word 文档转为 html
 * <p>
 * 简单文档阅读器，用于展示知识类文档。
 * <p>
 * 这是我们公司用的一种专用格式，table 用于展示代码样例。
 *
 * @author Mr.css
 * @version 2025-03-27 15:45
 */
public class DocsReader implements HtmlReader<InputStream> {
    public final Logger logger = LoggerFactory.getLogger(DocsReader.class);

    /**
     * body 元素读取
     */
    private final Writer writer;

    public DocsReader(Writer writer) {
        this.writer = writer;
    }

    /**
     * 文件输入流
     *
     * @param is 输入流
     * @throws IOException -
     */
    @Override
    public void read(InputStream is) throws IOException {
        // 各种各样的内容读取
        RunReader runReader = new RunReader(writer);
        BodyReader bodyReader = new BodyReader(writer);
        TableCodeReader tableReader = new TableCodeReader(writer);
        ParagraphReader paragraphReader = new ParagraphReader(writer);

        // 互相注入对象引用
        bodyReader.setTableReader(tableReader);
        bodyReader.setParagraphReader(paragraphReader);
        paragraphReader.setReader(runReader);

        try (XWPFDocument document = new XWPFDocument(is)) {
            Iterator<IBodyElement> iterator = document.getBodyElementsIterator();
            bodyReader.read(iterator);
        }
    }
}
